<template>
  <div class="content">
    <!-- 优惠券分类 -->
    <div class="blueBox">
      <div class="operation">
        <b>选择券类型</b>
        <radio-group class="radioBox">
          <radio
            v-for="(item,index) in fruit"
            :key="index"
            :value="item.name"
            color="#2b7bf8"
            @click="radioClick(item.name,item.id)"
            :checked="item.checked"
            class="radio"
          >{{item.name}}</radio>
        </radio-group>
      </div>
      <div class="couponNameBox">
        <b>优惠券名称</b>
        <input
          class="nameInput"
          type="text"
          placeholder="请输入优惠券名称"
          maxlength="9999"
          v-model="couponData.couponTypeName"
          @change="couponTypeNameChange"
        >
        <span>添加名称方便识别和管理，不会显示在用户优惠券上。</span>
      </div>
      <div class="layout1Div">
        <b>领取门槛</b>
        <input
          type="number"
          placeholder="￥店内消费满多少元可领取"
          maxlength="9999"
          v-model="couponData.consumeAmount"
          @change="consumeAmountChange"
        >
      </div>
      <div class="layout1Div">
        <b>优惠券总量</b>
        <input
          type="number"
          placeholder="请输入优惠券总张数"
          maxlength="9999"
          v-model="couponData.number"
          @change="numberChange"
        >
      </div>
      <div class="kong"></div>
    </div>
    <!-- 满减条件 -->
    <div class="conditionBox">
      <div class="kong1"></div>
      <div class="box1" v-if="fruit[0].checked">
        <div class="layout1Div">
          <b>满减条件</b>
          <input
            type="number"
            placeholder="￥请输入满减条件"
            maxlength="9999"
            v-model="couponData.reachAmount"
            @change="reachAmountChange"
          >
        </div>
        <div class="layout1Div">
          <b>满减金额</b>
          <input
            type="number"
            placeholder="￥请输入满减金额"
            maxlength="9999"
            v-model="couponData.reduceAmount"
            @change="reduceAmountChange"
          >
        </div>
      </div>
      <div class="box2" v-if="fruit[1].checked">
        <div class="layout1Div">
          <b>抵扣现金</b>
          <input
            type="number"
            placeholder="￥请输入抵扣现金"
            maxlength="9999"
            v-model="couponData.cashAmount"
            @change="cashAmountChange"
          >
        </div>
      </div>
      <div class="box3" v-if="fruit[2].checked">
        <div class="layout1Div">
          <b>折扣率</b>
          <input
            max="10"
            min="0"
            type="digit"
            placeholder="请输入折扣"
            maxlength="3"
            :value="couponData.discountRate"
            v-model="couponData.discountRate"
            @change="discountRateChange"
          >
          <span>折</span>
        </div>
      </div>
      <div class="kong"></div>
    </div>
    <!-- 时间 -->
    <div class="dateBox">
      <div class="kong1"></div>
      <div class="layout1Div">
        <b>领取后时效时间</b>
        <input
          type="number"
          placeholder="用户领券后失效天数"
          maxlength="9999"
          v-model="couponData.validDate"
          @change="validDateChange"
        >
      </div>
      <!-- 开始时间 -->
      <div class="layout1Div">
        <b>优惠券有效时间</b>
        <picker
          mode="multiSelector"
          @change="bindStartMultiPickerChange"
          @columnchange="bindStartColumnchange"
          :value="multiStartIndex"
          :range="startDatePickerArr"
        >
          <input
            mode="wrapped"
            :value="couponData.validDateStart"
            placeholder="请选择时间"
            maxlength="999999"
            disabled
          >
        </picker>
      </div>
      <!-- 结束时间 -->
      <div class="layout1Div">
        <b></b>
        <picker
          mode="multiSelector"
          @change="bindOverMultiPickerChange"
          :value="multiOverIndex"
          :range="newMultiArray"
        >
          <input
            mode="wrapped"
            :value="couponData.validDateEnd"
            placeholder="请选择时间"
            maxlength="999999"
            disabled
          >
        </picker>
      </div>
      <div class="layout1Div">
        <b>发放状态</b>
        <i-switch :value="onOff" @change="onChange" slot="large">
          <view slot="open">开</view>
          <view slot="close">停</view>
        </i-switch>
      </div>
      <div class="kong"></div>
    </div>
    <div class="overBtnBox">
      <button v-if="!btnBool" @click="addOverClick">完成</button>
      <button v-if="btnBool " @click="editOverClick">编辑</button>
    </div>
  </div>
</template>

<script>
import { CREATE_COUPON_TYPE_API, UPDATE_COUPON_TYPE_API } from '@/api'
import { numberArr, lastDayOfMonth } from '@/utils'

export default {
  components: {},
  data () {
    return {
      fruit: [
        {
          id: '1',
          name: '满减券',
          checked: true
        },
        {
          id: '2',
          name: '现金券',
          checked: false
        },
        {
          id: '3',
          name: '折扣券',
          checked: false
        }
      ],
      couponData: {
        couponType: '1',
        validDateStart: '',
        validDateEnd: '',
        couponTypeEnum: 'REACH_REDUCE'
      }, // 数据
      form: {
        timeStart: '',
        timeOver: '',
        validTime: ''
      },
      multiStartIndex: [0, 0, 0, 0, 0],
      multiOverIndex: [0, 0, 0, 0, 0],
      btnBool: false, // false的时候是新增，teru的时候是编辑
      onOff: false,
      timeBool: false,
      dataNum: null,

      startData: { year: 2019, month: 1 },
      endDate: { year: '', month: '' }
    }
  },
  created () {},
  computed: {
    account () {
      return this.$cookie.get('account')
    },
    newMultiArray () {
      let array = []
      const date = new Date()
      const years = []
      const months = []
      const days = []
      const hours = []
      const minutes = []
      const second = []
      for (let i = date.getFullYear(); i <= date.getFullYear() + 10; i++) {
        years.push('' + i)
      }
      array.push(years)

      for (let i = 1; i <= 12; i++) {
        if (i < 10) {
          i = '0' + i
        }
        months.push('' + i)
      }
      array.push(months)

      for (let j = 0; j < array[1].length; j++) {
        console.log(array[1][j])
        switch (array[1][j]) {
          case '01':
          case '03':
          case '05':
          case '07':
          case '08':
          case '10':
          case '12':
            this.dataNum = 30
            break
          case '04':
          case '06':
          case '09':
          case '11':
            this.dataNum = 31
            break
          case '02':
            this.dataNum = 28
            break
        }
      }
      console.log('dataNum', this.dataNum)

      for (let i = 1; i <= this.dataNum; i++) {
        if (i < 10) {
          i = '0' + i
        }
        days.push('' + i)
      }
      array.push(days)
      for (let i = 0; i < 24; i++) {
        if (i < 10) {
          i = '0' + i
        }
        hours.push('' + i)
      }
      array.push(hours)
      for (let i = 0; i < 60; i++) {
        if (i < 10) {
          i = '0' + i
        }
        minutes.push('' + i)
      }
      array.push(minutes)
      for (let i = 0; i < 60; i++) {
        if (i < 10) {
          i = '0' + i
        }
        second.push('' + i)
      }
      array.push(second)
      return array
    },
    startDatePickerArr () {
      let yearNow = new Date().getFullYear()
      let year = numberArr(yearNow - 10, yearNow)
      let month = numberArr(1, 12)
      let dayEnd = lastDayOfMonth(this.startData.year, this.startData.month)
      let day = numberArr(1, dayEnd)
      let hour = numberArr(0, 23)
      let minute = numberArr(0, 59)
      let second = numberArr(0, 59)
      return [year, month, day, hour, minute, second]
    },
    endDatePickerArr () {
      return ''
    }
  },

  onShow () {
    this.init()
    console.log('date', this.newMultiArray)
  },
  methods: {
    radioClick (name, value) {
      const vm = this
      vm.couponData.couponType = value
      if (vm.couponData.couponType === '1') {
        vm.couponData.couponTypeEnum = 'REACH_REDUCE'
      }
      if (vm.couponData.couponType === '2') {
        vm.couponData.couponTypeEnum = 'CASH'
      }
      if (vm.couponData.couponType === '3') {
        vm.couponData.couponTypeEnum = 'DISCOUNT'
      }
      // this.couponData.discountRate = '' // 如果需要切换的时候清空输入折扣就放开这里
      vm.fruit.forEach(_ => {
        if (_.id === value) {
          _.checked = true
        } else {
          _.checked = false
        }
      })
    }, // 点击选项
    couponTypeNameChange (e) {
      this.couponData.couponTypeName = e.mp.detail.value
    }, // 优惠券名称change
    consumeAmountChange (e) {
      this.couponData.consumeAmount = e.mp.detail.value
    }, // 领取门槛change
    numberChange (e) {
      this.couponData.number = e.mp.detail.value
    }, // 优惠券总量change
    // ---------------------满减卷的-----------------------------
    reachAmountChange (e) {
      this.couponData.reachAmount = Number(e.mp.detail.value)
    }, // 满减条件change
    reduceAmountChange (e) {
      this.couponData.reduceAmount = Number(e.mp.detail.value)
    }, // 满减金额change
    // ---------------------满减卷的-----------------------------
    // ---------------------现金卷的-----------------------------
    cashAmountChange (e) {
      this.couponData.cashAmount = e.mp.detail.value
    }, // 抵扣现金change
    // ---------------------现金卷的-----------------------------
    // ---------------------折扣券的-----------------------------
    discountRateChange (e) {
      // this.couponData.discountRate = Number(e.mp.detail.value) * 0.01
      if (Number(e.mp.detail.value) > 10) {
        this.$toast('折扣不能大于10折')
      } else if (Number(e.mp.detail.value) < 0) {
        this.$toast('折扣不能小于0折')
      } else {
        this.couponData.discountRate = Number(e.mp.detail.value)
      }
    }, // 折扣change
    // ---------------------折扣券的-----------------------------

    validDateChange (e) {
      this.couponData.validDate = e.mp.detail.value
    }, // 优惠券有效时间change

    bindStartMultiPickerChange (e) {
      this.multiStartIndex = e.target.value
      const index = this.multiStartIndex
      const year = this.newMultiArray[0][index[0]]
      const month = this.newMultiArray[1][index[1]]
      const day = this.newMultiArray[2][index[2]]
      const hour = this.newMultiArray[3][index[3]]
      const minute = this.newMultiArray[4][index[4]]
      const second = this.newMultiArray[5][index[5]]
      this.couponData.validDateStart =
        year +
        '-' +
        month +
        '-' +
        day +
        ' ' +
        hour +
        ':' +
        minute +
        ':' +
        second
      this.timeDate()
    }, // 获取开始时间日期
    bindOverMultiPickerChange (e) {
      const vm = this
      if (vm.couponData.validDateStart === '') {
        vm.$toast('还没有选择开始时间呢~~~')
      } else {
        vm.multiOverIndex = e.target.value
        const index = vm.multiOverIndex
        const year = vm.newMultiArray[0][index[0]]
        const month = vm.newMultiArray[1][index[1]]
        const day = vm.newMultiArray[2][index[2]]
        const hour = vm.newMultiArray[3][index[3]]
        const minute = vm.newMultiArray[4][index[4]]
        const second = vm.newMultiArray[5][index[5]]
        vm.couponData.validDateEnd =
          year +
          '-' +
          month +
          '-' +
          day +
          ' ' +
          hour +
          ':' +
          minute +
          ':' +
          second
        vm.timeDate()
      }
    }, // 获取结束时间日期
    bindStartColumnchange (e) {
      // console.log(e.mp.detail.column)
      let idx = e.target.column
      let idx2 = e.target.value

      if (idx === 0) {
        console.log('year:', this.newMultiArray[idx][idx2])
        this.startData.year = this.newMultiArray[idx][idx2] * 1
      } else if (idx === 1) {
        console.log('month:', this.newMultiArray[idx][idx2])
        this.startData.month = this.newMultiArray[idx][idx2] * 1
      }
    },
    timeDate () {
      const vm = this
      let date1 = new Date(vm.couponData.validDateStart)
      let date2 = new Date(vm.couponData.validDateEnd)
      let date = date2.getTime() - date1.getTime()
      var hours = Math.floor(date / (3600 * 1000))
      vm.form.validTime = hours
      if (date < 0) {
        vm.timeBool = false
      } else {
        vm.timeBool = true
      }
    }, // 时间转化
    addOverClick () {
      const vm = this
      if (vm.timeBool) {
        let params = { ...vm.couponData }
        params.shopId = vm.account.shopId
        params.couponTypeEnum = vm.couponData.couponTypeEnum
        params.discountRate = vm.couponData.discountRate * 0.1
        if (params.discountRate > 1) {
          this.$toast('折扣不能大于10折')
          return false
        } else if (params.discountRate < 0) {
          this.$toast('折扣不能小于0折')
          return false
        }
        if (params.reachAmount < params.reduceAmount) {
          this.$toast('满减金额不能大于满减条件')
          return false
        }
        CREATE_COUPON_TYPE_API(params)
          .then(r => {
            if (r.data.code === '0' && r.data.data) {
              vm.$alert('新增优惠券成功').then(r => {
                // vm.$router.replace(
                //   '/pages/mine/cloud-account/step2/company/main'
                // )
                vm.$router.go(-1)
              })
            } else {
              vm.$toast(r.data.message)
            }
          })
          .catch(e => {
            console.info(e)
          })
      } else {
        vm.$toast('时间选择有误~~~')
      }
    }, // 新增完成按钮
    editOverClick () {
      const vm = this
      if (vm.timeBool) {
        let params = { ...vm.couponData }
        params.shopId = vm.account.shopId
        params.couponTypeEnum = vm.couponData.couponTypeEnum
        params.discountRate = vm.couponData.discountRate * 0.1
        if (params.discountRate > 1) {
          this.$toast('折扣不能大于10折')
          return false
        } else if (params.discountRate < 0) {
          this.$toast('折扣不能小于0折')
          return false
        }
        if (params.reachAmount < params.reduceAmount) {
          this.$toast('满减金额不能大于满减条件')
          return false
        }
        UPDATE_COUPON_TYPE_API(params)
          .then(r => {
            if (r.data.code === '0' && r.data.data) {
              vm.$alert('编辑优惠券成功').then(r => {
                // vm.$router.replace(
                //   '/pages/mine/cloud-account/step2/company/main'
                // )
                vm.$router.go(-1)
              })
            } else {
              vm.$toast(r.data.message)
            }
          })
          .catch(e => {
            console.info(e)
          })
      } else {
        vm.$toast('时间选择有误~~~')
      }
    }, // 编辑完成按钮
    judgeIsAddAndEdit () {
      let val = this.$root.$mp.query.val
      if (val === '1') {
        this.timeBool = true // 如果是编辑状态，初始化时就变为true
        this.couponData = JSON.parse(this.$cookie.get('couponData'))
        let couponType = this.couponData.couponType
        this.couponData.discountRate = this.couponData.discountRate * 10
        this.btnBool = true
        if (this.couponData.state === '0') {
          this.onOff = true
        } else {
          this.onOff = false
        }
        if (this.couponData.couponType === '1') {
          this.couponData.couponTypeEnum = 'REACH_REDUCE'
        }
        if (this.couponData.couponType === '2') {
          this.couponData.couponTypeEnum = 'CASH'
        }
        if (this.couponData.couponType === '3') {
          this.couponData.couponTypeEnum = 'DISCOUNT'
        }
        this.fruit.forEach(_ => {
          if (_.id === couponType) {
            _.checked = true
          } else {
            _.checked = false
          }
        })
      } else {
        this.couponData = {
          couponType: '1',
          validDateStart: '',
          validDateEnd: '',
          couponTypeEnum: 'REACH_REDUCE',
          state: '0'
        }
        this.btnBool = false
        this.onOff = true // 新增的时候默认是开
      }
    }, // 判断编辑/新增
    init () {
      this.judgeIsAddAndEdit()
    },
    onChange (e) {
      let value = e.mp.detail.value
      console.log(e.mp.detail.value)
      this.onOff = value
      if (value) {
        this.couponData.state = '0'
      } else {
        this.couponData.state = '1'
      }
    } // 开关
  }
}
</script>

<style lang="scss">
@import 'static/styles/color.scss';
.content {
  background: #fffffd;
  .blueBox {
    width: calc(100% - 20px);
    margin: auto;
    min-height: 80px;
    box-shadow: 0 0 8px lighten($blue, 20%);
    transform: translateY(10px);
    .operation {
      b {
        font-size: 14px;
        font-weight: 500;
        color: #000;
        padding: 18px 0 0 20px;
      }
      .radioBox {
        width: calc(100% - 80px);
        margin: 10px auto 0;
        font-size: 12px;
        color: #000;
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
    }
    .couponNameBox {
      b {
        font-size: 14px;
        font-weight: 500;
        color: #000;
        padding: 18px 0 0 20px;
      }
      .nameInput {
        background: #edf0f5;
        width: calc(100% - 80px);
        height: 20px;
        font-size: 14px;
        padding: 8px 20px;
        color: #000;
        margin: 10px auto 0;
        border: 1px solid #e3e3e5;
        border-radius: 4px;
      }
      span {
        font-size: 12px;
        color: #a0a0a0;
        margin: auto;
        padding: 18px 0 0 20px;
      }
    }
    .layout1Div {
      width: calc(100% - 40px);
      height: 40px;
      margin: 15px auto 0;
      display: flex;
      justify-content: space-between;
      align-items: center;
      b {
        font-size: 14px;
        font-weight: 500;
        color: #000;
      }
      input {
        width: 190px;
        background: #edf0f5;
        height: 20px;
        font-size: 14px;
        padding: 8px 20px;
        color: #000;
        border: 1px solid #e3e3e5;
        border-radius: 4px;
      }
    }
    .kong {
      height: 25px;
    }
  }
  .conditionBox {
    width: calc(100% - 20px);
    margin: 20px auto;
    box-shadow: 0 0 8px lighten($blue, 20%);
    transform: translateY(10px);
    .box1 {
      min-height: 80px;
      .layout1Div {
        width: calc(100% - 40px);
        height: 40px;
        margin: 15px auto 0;
        display: flex;
        justify-content: space-between;
        align-items: center;
        b {
          font-size: 14px;
          font-weight: 500;
          color: #000;
        }
        input {
          width: 190px;
          background: #edf0f5;
          height: 20px;
          font-size: 14px;
          padding: 8px 20px;
          color: #000;
          border: 1px solid #e3e3e5;
          border-radius: 4px;
        }
      }
    }
    .box2 {
      min-height: 40px;
      align-items: center;
      .layout1Div {
        width: calc(100% - 40px);
        height: 40px;
        margin: 15px auto 0;
        display: flex;
        justify-content: space-between;
        align-items: center;
        b {
          font-size: 14px;
          font-weight: 500;
          color: #000;
        }
        input {
          width: 190px;
          background: #edf0f5;
          height: 20px;
          font-size: 14px;
          padding: 8px 20px;
          color: #000;
          border: 1px solid #e3e3e5;
          border-radius: 4px;
        }
      }
    }
    .box3 {
      min-height: 40px;
      align-items: center;
      .layout1Div {
        width: calc(100% - 40px);
        height: 40px;
        margin: 15px auto 0;
        display: flex;
        justify-content: flex-start;
        align-items: center;
        b {
          font-size: 14px;
          font-weight: 500;
          color: #000;
        }
        input {
          width: 90px;
          background: #edf0f5;
          height: 20px;
          font-size: 14px;
          padding: 8px 20px;
          color: #000;
          border: 1px solid #e3e3e5;
          border-radius: 4px;
          margin: 0 10px 0 30px;
        }
        span {
          font-size: 14px;
          font-weight: 500;
          color: #000;
        }
      }
    }
    .kong1 {
      height: 18px;
    }
    .kong {
      height: 25px;
    }
  }
  .dateBox {
    width: calc(100% - 20px);
    margin: auto;
    min-height: 80px;
    box-shadow: 0 0 8px lighten($blue, 20%);
    transform: translateY(10px);
    .layout1Div {
      width: calc(100% - 40px);
      height: 40px;
      margin: 15px auto 0;
      display: flex;
      justify-content: space-between;
      align-items: center;
      b {
        font-size: 14px;
        font-weight: 500;
        color: #000;
      }
      input {
        width: 150px;
        background: #edf0f5;
        height: 20px;
        font-size: 14px;
        padding: 8px 20px;
        color: #000;
        border: 1px solid #e3e3e5;
        border-radius: 4px;
      }
    }
    .kong1 {
      height: 18px;
    }
    .kong {
      height: 25px;
    }
  }
  .overBtnBox {
    width: 100%;
    button {
      margin-top: 30px;
      width: 100%;
      height: 40px;
      background: #e51c23;
      color: #fff;
      font-size: 14px;
      line-height: 40px;
      text-align: center;
      border-radius: 0;
    }
  }
}
</style>
